package com.hspedu.newData.dmsxl.栈;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-25 
 * @Version: 1.0
 */

public class LC394字符串解码 {

    // todo 两个队列，一个存复制的次数，一个存待重复的串
    public String decodeString(String s) {

        Deque<Integer> stack_num = new ArrayDeque<>();
        Deque<String> stack_res = new ArrayDeque<>();

        StringBuilder res = new StringBuilder();
        int num = 0;

        for (char c : s.toCharArray()) {
            if (c=='['){
                // 将num和res转入队列，num是这一轮的循环次数，res是上一轮已经解码完成的结果
                stack_num.push(num);
                stack_res.push(res.toString());

                // 更新
                num = 0;
                res = new StringBuilder();
            } else if (c==']') {

                // 上一轮结果
                String res_last = stack_res.pop();

                // 这一轮num
                Integer pop = stack_num.pop();

                StringBuilder temp = new StringBuilder();
                for (int i = 0; i < pop; i++) {
                    temp.append(res);
                }
                res = new StringBuilder(res_last + temp);
            } else if (c >= '0' && c <= '9') {
                num = num*10 + (c - '0');
            }else {
                res.append(c);
            }
        }
        return res.toString();
    }


    @Test
    public void test() {
        // 测试代码

        decodeString("3[a]2[bc]");
    }
}
